<template>
  <div class="form-edit-dialog display-flex w-full h-full" style="justify-content: flex-start;overflow: hidden">
    <div class="inv-data-box right-border h-full flex-1" style="overflow: auto">
      <a-tree
        :selectedKeys="invDataSelected"
        ref="invDataTree"
        v-if="invDataTreeBuild && invDataTreeBuild.length > 0"
        :tree-data="invDataTreeBuild"
        :expandedKeys="invDefaultExpandedKeys"
        @expand="(selectedKeys,e) => handlerDataExpend(selectedKeys,e,'invDefaultExpandedKeys')"
        @select="(selectedKeys,e) => handlerDataSelect(selectedKeys,e,'invDataSelected')"
        :replaceFields="{title:'code',key:'id'}">
        <template slot="title" slot-scope="record">
          {{ record.code + ((record.name && record.code !== record.name) ? '(' + record.name + ')' : '') }}
        </template>
      </a-tree>
    </div>
    <div class="biz-data-box right-border h-full flex-1" style="overflow: auto">
      <a-tree
        :selectedKeys="bizDataSelected"
        ref="bizDataTree"
        v-if="invDataTree && invDataTree.length > 0"
        :tree-data="dataModelList"
        :loadData="(node) => loadBizDataModelData(node)"
        :loadedKeys="bizDataModelLoadKeys"
        :expandedKeys="bizDefaultExpandedKeys"
        @expand="(selectedKeys,e) => handlerDataExpend(selectedKeys,e,'bizDefaultExpandedKeys')"
        @select="(selectedKeys,e) => handlerDataSelect(selectedKeys,e,'bizDataSelected')"
        :replaceFields="{title:'metaDataObject',key:'id'}">
        <template slot="title" slot-scope="record">
          {{ record.metaDataObject + '(' + (record.objectName || '') + ')' }}
        </template>
      </a-tree>
    </div>
    <div class="config-box h-full flex-1 display-flex-column">
      <a-radio-group class="config-item-box" name="radioGroup" :default-value="1" v-model="selectConfigType">
        <a-radio value="text">
          <div class="list-item">
            <div class="item-name">文本</div>
          </div>
        </a-radio>
        <a-radio value="date">
          <div class="list-item">
            <div class="item-name">日期</div>
          </div>
        </a-radio>
        <a-radio value="unit">
          <div class="list-item display-flex" style="justify-content: flex-start">
            <div class="item-name m-r-sm">单位转换</div>
            <div class="item-content" v-show="selectConfigType === 'unit'">
              <a-select
                v-model="selectUnit"
                class="selector-item"
                style="width: 300px"
              >
                <a-select-option value="hectare-squareMeter">
                  公顷 → 平方米
                </a-select-option>
                <a-select-option value="squareMeter-hectare">
                  平方米 → 公顷
                </a-select-option>
              </a-select>
            </div>
          </div>
        </a-radio>
        <a-radio value="dictionary">
          <div class="list-item display-flex" style="justify-content: flex-start">
            <div class="item-name m-r-sm">数据字典</div>
            <div class="item-content" v-show="selectConfigType === 'dictionary'">
              <a-select
                show-search
                class="selector-item"
                style="width: 300px"
                :filter-option="filterDicOption"
                v-model="selectDicId"
              >
                <a-select-option v-for="dic in dicList" :key="dic.id" :value="dic.id">
                  {{ dic.name }}
                </a-select-option>
              </a-select>
            </div>
          </div>
        </a-radio>
        <a-radio value="complexity">
          <div class="list-item display-flex" style="justify-content: flex-start">
            <div class="item-name m-r-sm">复杂映射</div>
            <div class="item-content" v-show="selectConfigType === 'complexity'">
              <a-select
                v-model="selectTemplateId"
                show-search
                class="selector-item m-r-sm"
                :disabled="true"
                style="width: 250px">
                <a-select-option v-for="item in templateList" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <a-button type="primary" @click="handlerChoseComplexity">选择</a-button>
            </div>
          </div>
        </a-radio>
      </a-radio-group>
      <div class="extend-fields-box m-t-sm">
        <div class="item-name m-l-xs">拓展字段:</div>
        <div class="item-content">
          <a-table
            style="margin: 10px 0 0 5px;"
            bordered
            :scroll="{ x: false, y: '200px' }"
            :data-source="extendFieldList"
            :columns="extentFieldListColumn">
            <template slot="code" slot-scope="text, record">
              <a-input v-model="record.code"/>
            </template>
          </a-table>
        </div>
        <div class="w-full" style="height: 10px"></div>
        <div class="item-button display-flex" style="justify-content: flex-end">
          <a-button class="m-r-sm" type="primary" @click="handlerAddExtendField">新增行</a-button>
          <a-button @click="handlerRemoveExtendField">删除行</a-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import dapProjectService from '@/api/dapProjectService'
import businessService from '@/api/businessService'
import dicService from '@/api/dicService'
import editableCell from '@v/investmentOnline/investmentPlatform/EditableCell.vue'
import { getColumns } from '@/api/tableColumns'
import dataMappingService from '@/api/dataMappingService'

export default {
  name: 'FormEditDialog',
  components: { editableCell },
  props: {
    businessType: {
      type: Object,
      default: () => {
        return {}
      }
    },
    category: {
      type: String,
      default: () => {
        return ''
      }
    },
    sourceId: {
      type: Number,
      default: () => {
        return 0
      }
    }
  },
  data () {
    return {
      invDataTree: [],
      dataModelList: [],
      bizDataModelLoadKeys: [],
      bizDefaultExpandedKeys: [],
      dicList: [],
      extendFieldList: [],
      selectConfigType: 'text',
      selectDicId: undefined,
      selectUnit: undefined,
      templateList: [],
      selectTemplateId: undefined,
      selectTemplateJson: undefined,
      invDataSelected: [],
      bizDataSelected: [],
      invDataSelectedObj: {},
      bizDataSelectedObj: {},
      invDefaultExpandedKeys: [],
      sourceInfo: {},
      invDataTreeBuild: []
    }
  },
  computed: {
    extentFieldListColumn () {
      return getColumns('multiFormSelected')
    }
  },
  async mounted () {
    if (this.sourceId) {
      await this.getSourceInfo()
    }
    this.listInvestmentItemFormListByTypeSource()
    this.listBizFormDataList()
    this.listDic()
    this.listAllDataMappingTemplates()
  },
  methods: {
    buildInvDataTree (invDataTree, needExpend) {
      const codeMap = {}
      const result = []
      const invDataList = []
      this.treeForEach(invDataTree, 'children', null, (item, parent) => {
        const copy = this._.cloneDeep(item)
        copy.children = []
        if (!item.parent_code) {
          codeMap[item.code] = copy
          result.push(copy)
        } else {
          invDataList.push(copy)
        }
      })
      invDataList.forEach(item => {
        const parent = codeMap[item.parent_code]
        if (parent) {
          if (!parent.children) {
            parent.children = []
          }
          parent.isLeaf = false
          parent.children.push(item)
          if (needExpend) {
            const findExt = this._.find(this.invDefaultExpandedKeys, it => it === parent.id)
            if (!findExt) {
              this.invDefaultExpandedKeys.push(parent.id)
            }
          }
        }
      })
      return result
    },
    async listAllDataMappingTemplates () {
      const data = await dataMappingService.listAllDataMappingTemplates()
      this.templateList = data
    },
    handlerChoseComplexity () {
      const props = {
        templateList: this.templateList
      }
      if (this.selectTemplateId) {
        props.sourceTemplateId = this.selectTemplateId
      }
      if (this.selectTemplateJson) {
        props.sourceTemplateJson = this.selectTemplateJson
      }
      const that = this
      this.$dialog({
        title: '复杂映射配置',
        content: () => import('../dataMapping/DataMappingChoseDialog.vue'),
        width: '700px',
        bodyStyle: { height: '400px', padding: '0' },
        centered: true,
        maskClosable: false,
        okButtonProps: {},
        props: props,
        model: {},
        on: {
          async ok (ctl) {
            const dialogCtl = ctl.getDialogCtl()
            const selectTemplate = dialogCtl.selectTemplate
            const templateJson = dialogCtl.templateJson
            if (!selectTemplate) {
              that.$message.warning('请选择对应模板')
              return
            }
            if (!templateJson) {
              that.$message.warning('请设置对应json信息')
              return
            }
            let isError = false
            try {
              JSON.parse(templateJson)
            } catch (e) {
              isError = true
            }
            if (isError) {
              that.$message.error('JSON信息非法,请重新编辑')
              return
            }
            that.selectTemplateId = selectTemplate
            that.selectTemplateJson = JSON.stringify(JSON.parse(templateJson))
            ctl.closeDialog()
          }
        }
      })
    },
    initTableId (itemType, category) {
      if (this.businessType.item_code === 'ITEM_LHYS') {
        if (category === 'common') {
          return itemType
        }
      } else {
        // 注销
        if (category === 'des') {
          if (itemType === 'system') {
            return 'desSystem'
          }
          if (itemType === 'business') {
            return 'desBusiness'
          }
        }

        // 延期/变更
        if (category === 'ext') {
          if (itemType === 'system') {
            return 'extSystem'
          }
          if (itemType === 'business') {
            return 'extBusiness'
          }
        }

        if (category === 'common') {
          if (itemType === 'system') {
            return 'commonSystem'
          }
          if (itemType === 'business') {
            return 'commonBusiness'
          }
        }
      }
    },
    async getSourceInfo () {
      const data = await dapProjectService.getBusinessItemFormMapById(this.sourceId)
      this.sourceInfo = data
      const tableId = this.initTableId(data.itemType, data.category)
      const invDataLog = {
        tableId: tableId,
        tableName: tableId,
        field: data.code,
        parentCode: data.parentCode
      }
      const bizDataLog = {
        tableName: data.businessTable,
        field: data.businessField
      }
      localStorage.setItem('invDataSelected', JSON.stringify(invDataLog))
      localStorage.setItem('bizDataSelected', JSON.stringify(bizDataLog))
      this.selectConfigType = data.adaptFieldType
      this.selectDicId = data.dictionaryID
      this.selectUnit = data.unit
      this.selectTemplateId = data.templateId
      this.selectTemplateJson = data.templateJson
      if (data.multiConfig) {
        const multiConfig = JSON.parse(data.multiConfig)
        multiConfig.forEach(item => {
          item.id = Number((new Date()))
        })
        this.extendFieldList = multiConfig
      }
    },
    treeForEach (list, childKey, parent, callback) {
      list.forEach(item => {
        callback(item, parent)
        if (item[childKey] && item[childKey].length > 0) {
          this.treeForEach(item[childKey], childKey, item, callback)
        }
      })
    },
    handlerDataExpend (selectedKeys, e, key) {
      this[key] = selectedKeys
    },
    handlerDataSelect (selectedKeys, e, key) {
      const dataRef = e.node.dataRef
      if (!dataRef.nodeType || dataRef.nodeType !== 'field') {
        this.$message.warning('当前非变量节点,请正确选择')
        this[key] = []
        this[key + 'Obj'] = {}
        return
      }
      this[key] = selectedKeys
      this[key + 'Obj'] = dataRef
      const selectLog = {
        tableName: dataRef.table_name || dataRef.tableName,
        field: dataRef.code || dataRef.metaDataObject,
        type: key,
        tableId: dataRef.tableId,
        parentCode: dataRef.parent_code
      }
      localStorage.setItem(key, JSON.stringify(selectLog))
    },
    getSaveData () {
      const multiConfig = []
      let isError = false
      this.extendFieldList.forEach(item => {
        if (!item.code) {
          isError = true
        }
        multiConfig.push({ code: item.code, sortNum: item.sortNum })
      })
      const result = {
        state: false,
        data: null
      }
      if (isError) {
        this.$message.warning('请正确配置拓展字段')
        return result
      }
      if (!this.category) {
        this.$message.warning('未获取到字段事项分类,请联系管理员')
        return result
      }
      if (!this.invDataSelectedObj.nodeType) {
        this.$message.warning('请选择正确的3.0系统表单字段')
        return result
      }
      if (this.invDataSelectedObj.category !== this.category) {
        this.$message.warning('流程类型不一致,请重新选择')
        return result
      }
      if (!this.bizDataSelectedObj.nodeType) {
        this.$message.warning('请选择正确的业务系统表单字段')
        return result
      }
      if (!this.selectConfigType) {
        this.$message.warning('请选择正确的配置字段类型')
        return result
      }
      if (this.selectConfigType === 'dictionary') {
        if (!this.selectDicId) {
          this.$message.warning('请选择正确的数据字典')
          return result
        }
      }
      if (this.selectConfigType === 'unit') {
        if (!this.selectUnit) {
          this.$message.warning('请选择正确的单位转化类型')
          return result
        }
      }
      if (this.selectConfigType === 'complexity') {
        if (!this.selectTemplateId || !this.selectTemplateJson) {
          this.$message.warning('请设置正确的复杂映射转化信息')
          return result
        }
      }
      const parmas = {
        businessItemMapId: this.businessType.id,
        businessTable: this.bizDataSelectedObj.tableName,
        businessField: this.bizDataSelectedObj.metaDataObject,
        itemFormId: this.invDataSelectedObj.id,
        itemCode: this.invDataSelectedObj.item_code,
        code: this.invDataSelectedObj.code,
        itemName: this.businessType.item_name,
        itemType: this.invDataSelectedObj.table_name,
        name: this.invDataSelectedObj.name,
        adaptFieldType: this.selectConfigType,
        parentCode: this.invDataSelectedObj.parent_code,
        subTable: 0, // 默认都为非子表
        dictionaryID: this.selectDicId,
        source: this.businessType.source,
        multiConfig: JSON.stringify(multiConfig),
        expression: null,
        unit: this.selectUnit,
        category: this.category,
        templateId: this.selectTemplateId,
        templateJson: this.selectTemplateJson
      }
      if (this.sourceId) {
        parmas.id = this.sourceId
      }
      result.state = true
      result.data = parmas
      return result
    },
    handlerAddExtendField () {
      this.extendFieldList.push({ id: Number((new Date())), code: '', sortNum: this.extendFieldList.length + 1 })
    },
    handlerRemoveExtendField () {
      this.extendFieldList.pop()
    },
    filterDicOption (input, option) {
      const find = this._.find(this.dicList, item => item.id === option.key)
      return find.name.indexOf(input) >= 0
    },
    async listDic () {
      const data = await dicService.searchDictionary()
      this.dicList = data.rows
    },
    async loadBizDataModelData (node, after) {
      const data = await businessService.getDataObjectDetail(node.dataRef.id)
      data.forEach(item => {
        item.metaDataObject = item.metadataobjectitem
        item.objectName = item.objdetailname
        item.nodeType = 'field'
        item.isLeaf = true
        item.tableName = node.dataRef.metaDataObject
      })
      this.bizDataModelLoadKeys.push(node.dataRef.id)
      node.dataRef.children = data
      if (after) {
        after(node.dataRef)
      }
    },
    async listBizFormDataList () {
      let businessId = ''
      if (this.category === 'des') {
        businessId = '2c92b0e688b4f91b0188b771bdd50003'
      } else {
        businessId = this.businessType.businessId
      }
      const data = await businessService.getBusinessById(businessId)
      const dataModelList = await businessService.getDataObject(data.dataModelId)
      dataModelList.forEach(item => {
        item.children = []
      })

      const dataLogStr = localStorage.getItem('bizDataSelected')
      if (dataLogStr) {
        const dataLog = JSON.parse(dataLogStr)
        const find = this._.find(dataModelList, item => item.metaDataObject === dataLog.tableName)
        if (find) {
          this.loadBizDataModelData({ dataRef: find }, (root) => {
            const children = root.children
            const findChild = this._.find(children, item => item.metaDataObject === dataLog.field)
            if (findChild) {
              this.bizDataSelected = [findChild.id]
              this.bizDataSelectedObj = findChild
              this.bizDefaultExpandedKeys = [find.id]
              this.bizDataModelLoadKeys = [findChild.id]
            }
          })
        }
      }
      this.dataModelList = dataModelList
    },
    async listInvestmentItemFormListByTypeSource () {
      let data = await dapProjectService.listInvestmentItemFormListByTypeSource({
        itemCode: this.businessType.item_code,
        source: this.businessType.source
      })
      const isLHYS = this.businessType.item_code === 'ITEM_LHYS'
      if (isLHYS) {
        data = data.filter(item => item.item_code === 'ITEM_LHYS')
      }
      const commonSystemList = []
      const commonBusinessList = []
      const extSystemList = []
      const extBusinessList = []
      const desSystemList = []
      const desBusinessList = []

      const matterFormDataList = []
      const projectDataList = []
      const matterDataList = []
      data.forEach(item => {
        item.nodeType = 'field'
        if (isLHYS) {
          if (item.category === 'common') {
            if (item.table_name === 'matterFormData') {
              item.tableId = 'matterFormData'
              matterFormDataList.push(item)
            }
            if (item.table_name === 'projectData') {
              item.tableId = 'projectData'
              projectDataList.push(item)
            }
            if (item.table_name === 'matterData') {
              item.tableId = 'matterData'
              matterDataList.push(item)
            }
          }
        } else {
          if (item.category === 'common') {
            if (item.table_name === 'business') {
              item.tableId = 'commonBusiness'
              commonBusinessList.push(item)
            }
            if (item.table_name === 'system') {
              item.tableId = 'commonSystem'
              commonSystemList.push(item)
            }
          }
          if (item.category === 'ext') {
            if (item.table_name === 'business') {
              item.tableId = 'extBusiness'
              extBusinessList.push(item)
            }
            if (item.table_name === 'system') {
              item.tableId = 'extSystem'
              extSystemList.push(item)
            }
          }
          if (item.category === 'des') {
            if (item.table_name === 'business') {
              item.tableId = 'desBusiness'
              desBusinessList.push(item)
            }
            if (item.table_name === 'system') {
              item.tableId = 'desSystem'
              desSystemList.push(item)
            }
          }
        }
      })
      let invDataTree = []
      if (isLHYS) {
        invDataTree = [
          {
            id: 'matterFormData',
            code: '事项表单数据',
            name: '',
            children: matterFormDataList
          },
          {
            id: 'projectData',
            code: '项目数据',
            name: '',
            children: projectDataList
          },
          {
            id: 'matterData',
            code: '事项数据',
            name: '',
            children: matterDataList
          }
        ]
        invDataTree = invDataTree.map(item => {
          item.nodeType = 'topNode'
          return item
        })
      } else {
        invDataTree = [
          {
            id: 'commonSystem',
            code: '系统表单',
            name: '',
            children: commonSystemList
          },
          {
            id: 'commonBusiness',
            code: '业务表单',
            name: '',
            children: commonBusinessList
          },
          {
            id: 'extSystem',
            code: '系统表单(延期/变更)',
            name: '',
            children: extSystemList
          },
          {
            id: 'extBusiness',
            code: '业务表单(延期/变更)',
            name: '',
            children: extBusinessList
          },
          {
            id: 'desSystem',
            code: '系统表单(注销)',
            name: '',
            children: desSystemList
          },
          {
            id: 'desBusiness',
            code: '业务表单(注销)',
            name: '',
            children: desBusinessList
          }
        ]
        invDataTree = invDataTree.map(item => {
          item.nodeType = 'topNode'
          return item
        })
      }
      const dataLogStr = localStorage.getItem('invDataSelected')
      if (dataLogStr) {
        const dataLog = JSON.parse(dataLogStr)
        if (dataLog.tableId) {
          const find = this._.find(invDataTree, item => item.id === dataLog.tableId)
          let childId = null
          if (find) {
            const children = find.children
            const findChild = this._.find(children, item => {
              if (dataLog.parentCode) {
                if (item.parent_code === dataLog.parentCode) {
                  childId = item.id
                  return item.code === dataLog.field
                } else {
                  return false
                }
              } else {
                return item.code === dataLog.field
              }
            })
            if (findChild) {
              this.invDefaultExpandedKeys = [find.id]
              if (childId) {
                this.invDefaultExpandedKeys.push(childId)
              }
              this.invDataSelected = [findChild.id]
              this.invDataSelectedObj = findChild
            }
          }
        }
      }

      this.invDataTree = invDataTree
      // 后补逻辑 组装树结构 兼容多级节点
      const invDataTreeBuild = []
      this.invDataTree.forEach(item => {
        const copy = this._.cloneDeep(item)
        copy.children = null
        let needExpand = false
        if (item.id.indexOf(this.category) >= 0) {
          needExpand = true
        }
        copy.children = this.buildInvDataTree(item.children, needExpand)
        invDataTreeBuild.push(copy)
      })
      this.invDataTreeBuild = invDataTreeBuild
    }
  }
}
</script>

<style scoped lang="less">
.form-edit-dialog {
  .right-border {
    border-right: 1px solid rgba(118, 119, 121, 0.4);
  }

  .config-box {
    padding: 10px;

    /deep/ .config-item-box {
      display: flex;
      flex-direction: column;

      .ant-radio-wrapper {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        height: 40px;
      }
    }
  }
}
</style>
